﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Data;
using System.Drawing;
using IntegrationAgent;
using System.Configuration;
using uMES.LeanManufacturing.DBUtility;

public partial class MaterialAppPopupForm : System.Web.UI.Page
{
    uMESMaterialBusiness material = new uMESMaterialBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESContainerBusiness  container = new uMESContainerBusiness();
    string businessName = "生产准备", parentName = "materialappinfo";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string type = Request.QueryString["type"];
            //获取已经发料的信息
            if (type == "1")
            {
                wgMaterialList.Columns.FromKey("LackQty").Hidden = false;
                btnMaterialApp.Visible = false;

            }
           
            Dictionary<string, string> popupData = (Dictionary<string, string>)Session["PopupData"];
            txtDispID.Text = popupData["ID"];
            txtDispProcessNo.Text = popupData["ProcessNo"];
            txtDispContainerName.Text = popupData["ContainerName"];
            txtDispContainerID.Text = popupData["ContainerID"];
            txtDispProductName.Text = popupData["ProductName"];
            txtDispProductID.Text = popupData["ProductID"];
            txtDispDescription.Text = popupData["Description"];
            txtDispQty.Text = popupData["Qty"];
            txtDispSpecName.Text = popupData["SpecName"];
            txtDispSpecID.Text = popupData["SpecID"];
            txtDispResourceName.Text = popupData["ResourceName"];
            txtDispPlannedCompletionDate.Text = popupData["PlannedCompletionDate"];
            txtDispMfgOrderName.Text = popupData["MfgOrderName"];
            txtDispWorkflowID.Value = popupData["WorkflowID"];

            Session["PopupData"] = null;

            string strProductID = txtDispProductID.Text;
            string strSpecID = txtDispSpecID.Text;
            int intQty = Convert.ToInt32(txtDispQty.Text);
            DataTable DT = material.GetMaterialListByProductID(strProductID, txtDispProcessNo.Text);
            DT.Columns.Add("RequireQty");
            DT.Columns.Add("StoreQty");
            DT.Columns["StoreQty"].DefaultValue = "0";
            DT.Columns.Add("ErpSendQty");//erp发料数
            DT.Columns.Add("LackQty");//缺件数
            
            //erp库存，缺件
            string strERPStatus = ConfigurationManager.AppSettings["ERPStatus"];
            ERPWebService erp = new ERPWebService();
            if (strERPStatus == "1")
            {      
                erp.Login();                
                //erp.Logout();
            }
            DataTable sendMaterialInfo = new DataTable();//erp已经发料信息
            if (type == "1") {
                sendMaterialInfo = material.GetMaterialSendByDispatchId(txtDispID.Text);
            }
            foreach (DataRow row in DT.Rows)
            {
                int intQtyRequired = Convert.ToInt32(row["QtyRequired"]);
                row["RequireQty"] = intQtyRequired * intQty;//需求数
                //erp库存
                if (strERPStatus == "1"&& !row["ProductName"].ToString().Contains("JE")) {
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    string strProductName = row["ProductName"].ToString();
                    para.Add("material", strProductName);
                    para.Add("warehouse", "");
                    para.Add("lot", "");
                    para.Add("project", "");

                    //从ERP查询物料库存
                    string strMessage = string.Empty;
                    DataTable dtStore = erp.GetMaterialInfo(para, out strMessage);

                    int intStoreQty = 0;
                    for (int i = 0; i < dtStore.Rows.Count; i++)
                    {
                        int intbaseQty = Convert.ToInt32(dtStore.Rows[i]["baseQty"].ToString());
                        int intlockQty = Convert.ToInt32(dtStore.Rows[i]["lockQty"].ToString());
                        intStoreQty += intbaseQty - intlockQty;
                    }

                    row["StoreQty"] = intStoreQty;
                }
                //缺件
                if (type == "1"&& sendMaterialInfo.Rows.Count>0)
                {
                    var sendQty = sendMaterialInfo.Compute("sum(qty)", "productname='" + row["productname"].ToString() + "'");
                    int sendQty2 = 0;
                    if (int.TryParse(sendQty.ToString(), out sendQty2)) {
                        row["ErpSendQty"] = sendQty2;
                        row["LackQty"] = intQtyRequired * intQty - sendQty2;
                    }
                }

            }

            wgMaterialList.DataSource = DT;
            wgMaterialList.DataBind();
        }
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }
    #endregion

    #region 提交按钮
    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            if (wgMaterialList.Rows.Count == 0)
            {
                ShowStatusMessage("物料列表为空，不允许提交物料申请", false);
                return;
            }

            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            //如果已经申请，则只需更新issendErp字段
            DataTable materialDt = container.GetTableInfo("materialappinfo", "dispatchinfoid", txtDispID .Text );
            if (materialDt.Rows.Count > 0) {
                common .ExecuteDataByEntity(new ExcuteEntity("materialappinfo", ExcuteType.update) { ExcuteFileds = new List<FieldEntity>() { new FieldEntity("issenderp", "0", FieldType.Str), new FieldEntity("erpreturnmsg", "", FieldType.Str) },
                    WhereFileds= new List<FieldEntity>() { new FieldEntity("dispatchinfoid", txtDispID .Text , FieldType.Str) }
                });

                Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
                #region 记录日志
                var ml = new MESAuditLog();
                ml.ContainerName = txtDispContainerName.Text ; ml.ContainerID = txtDispContainerID.Text;
                ml.ParentID = materialDt.Rows [0]["ID"].ToString() ; ml.ParentName = parentName;
                ml.CreateEmployeeID = userInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 1;
                ml.Description = "物料申请:" + "组件物料申请";
                common.SaveMESAuditLog(ml);
                #endregion
                return;
            }

            //物料列表
            DataTable dtMaterial = new DataTable();
            dtMaterial.Columns.Add("ProductID");
            dtMaterial.Columns.Add("ProductName");
            dtMaterial.Columns.Add("Qty");
            dtMaterial.Columns.Add("UOMID");
            dtMaterial.Columns.Add("Uom");
            dtMaterial.Columns.Add("MfgOrderName");
            dtMaterial.Columns.Add("ContainerName");//需求批次

            string strMfgOrderName = txtDispMfgOrderName.Text;
            for (int i = 0; i < wgMaterialList.Rows.Count; i++)
            {
                string strProductID = wgMaterialList.Rows[i].Cells.FromKey("ProductID").Value.ToString();
                string strProductName = wgMaterialList.Rows[i].Cells.FromKey("ProductName").Value.ToString();
                string strQty = wgMaterialList.Rows[i].Cells.FromKey("RequireQty").Value.ToString();

                DataRow row = dtMaterial.NewRow();
                row["ProductID"] = strProductID;
                row["ProductName"] = strProductName;
                row["Qty"] = strQty;
                row["UOMID"] = "";
                row["Uom"] = "";
                row["MfgOrderName"] = strMfgOrderName;
                row["ContainerName"] = wgMaterialList.Rows[i].Cells.FromKey("ContainerName").Text;
                dtMaterial.Rows.Add(row);
                if (strProductName.Contains("JE") && string.IsNullOrWhiteSpace(row["ContainerName"].ToString())) {
                    ShowStatusMessage("有自制件未提交入库,无法进行组件物料申请", false);
                    return;
                }
            }
            

            string strDispatchInfoID = txtDispID.Text;
            string strContainerID = string.Empty;
            string strContainerName = txtDispContainerName.Text;
            string strSpecID = txtDispSpecID.Text;
            string strProcessNo = txtDispProcessNo.Text;

            string strFullName = userInfo["FullName"];
            string strFactoryID = userInfo["FactoryID"];
            string strFactoryName = userInfo["FactoryName"];
            string strSubmitEmployeeID = userInfo["EmployeeID"];

            Dictionary<string, string> para = new Dictionary<string, string>();
            string strID = Guid.NewGuid().ToString();
            string strMaterialAppInfoName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            para.Add("MaterialAppInfoID", strID);
            para.Add("MaterialAppInfoName", strMaterialAppInfoName);
            para.Add("DispatchInfoID", strDispatchInfoID);
            para.Add("ContainerID", txtDispContainerID.Text);
            para.Add("ContainerName", strContainerName);
            para.Add("SpecID", strSpecID);
            para.Add("SpecNo", "");
            para.Add("SpecName", "");
            para.Add("FactoryID", strFactoryID);
            para.Add("ProcessNo", strProcessNo);
            para.Add("OprNo", "");
            para.Add("Type", "0");
            para.Add("SubmitEmployeeID", strSubmitEmployeeID);

            para.Add("MfgorderName", txtDispMfgOrderName.Text);
            para.Add("ProductID", "");
            para.Add("Qty", "");
            para.Add("WorkflowID", txtDispWorkflowID.Value);
            para["AppType"] = "1";

            string strSubmitDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            para.Add("SubmitDate", strSubmitDate);
            para.Add("Status", "0");
            para.Add("Notes", ""); para["AppType"] = "1";

           var result= material.AddMaterialAppInfo(para, dtMaterial);
            if (result == true)
            {
                Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
                #region 记录日志
                var ml = new MESAuditLog();
                ml.ContainerName = strContainerName; ml.ContainerID = txtDispContainerID.Text;
                ml.ParentID = strID; ml.ParentName = parentName;
                ml.CreateEmployeeID = userInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 0;
                ml.Description = "物料申请:" + "组件物料申请";
                common.SaveMESAuditLog(ml);
                #endregion
            }

            //向ERP发送物料申请
            /*
            Dictionary<string, string> p = new Dictionary<string, string>();
            p.Add("mesReqNo", strMaterialAppInfoName);
            p.Add("mesReqId", strID);
            p.Add("bizDate", strSubmitDate);
            p.Add("reqOrgUnit", strFactoryName);
            p.Add("applier", strFullName);
            p.Add("workOrder", strProcessNo);

            ERPWebService erp = new ERPWebService();
            string strMessage = string.Empty;
            erp.Login();
            Boolean result = erp.SendMaterialAppInfo(p, dtMaterial, out strMessage);
            erp.Logout();

            if (result == true)
            {
                Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
            }
            else
            {
                ShowStatusMessage(strMessage, false);
            }

            */
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion
}